package com.zhang.study.chapter03;

import java.util.Stack;

/**
 * 使用栈结构实现队列
 */
public class Code09_StackImplQueue {



    public static class MyQueue<T> {
        Stack<T> pushStack;
        Stack<T> popStack;

        public MyQueue() {
            this.pushStack = new Stack<>();
            this.popStack = new Stack<>();
        }

        public void pushToPop(){
            if(popStack.isEmpty()){
                while(!pushStack.isEmpty()){
                    popStack.push(pushStack.pop());
                }
            }
        }


        public void push(T item) {
            pushStack.push(item);
            pushToPop();
        }

        public T pop() {
            if (popStack.empty() && pushStack.empty()) {
                throw new RuntimeException("Queue is empty!");
            }
            pushToPop();
            return popStack.pop();
        }

        public T peek() {
            if (popStack.empty() && pushStack.empty()) {
                throw new RuntimeException("Queue is empty!");
            }
            pushToPop();
            return popStack.peek();
        }

    }

    public static void main(String[] args) {
        MyQueue<Integer> queue = new MyQueue<>();
        queue.push(1);
        queue.push(2);
        queue.push(3);
        queue.push(4);
        System.out.println(queue.pop());
        System.out.println(queue.pop());
        System.out.println(queue.pop());
        System.out.println(queue.pop());
    }





}
